package util

import (
	"bytes"
	"fmt"
	"image"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/disintegration/imageorient"

	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)

/**
获取图片信息
*/
func GetImgInfo(url string) (image.Image, error) {
	resp, err := http.Get(url)

	defer resp.Body.Close()
	if err != nil {
		return nil, err
	}
	img, _, err := imageorient.Decode(resp.Body)

	if err != nil {
		return nil, err
	}
	return img, nil
}

// 下载图片
func DownImg(url, localPath string) (imgName string, n int64, err error) {
	// CreateDir(localPath)
	path := strings.Split(url, "/")
	var name string
	if len(path) > 1 {
		name = path[len(path)-1]
	}
	imgName = name
	fmt.Println(name)
	localPath = localPath + name
	out, err := os.Create(localPath)
	defer out.Close()
	resp, err := http.Get(url)
	defer resp.Body.Close()

	pix, err := ioutil.ReadAll(resp.Body)
	n, err = io.Copy(out, bytes.NewReader(pix))

	return

}

/**
创建文件夹
*/
func CreateDir(dirName string) bool {
	err := os.Mkdir(dirName, 755)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}

/**
判断文件是否存在
*/
func IsDir(fileAddr string) bool {
	s, err := os.Stat(fileAddr)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return s.IsDir()
}
